from __future__ import absolute_import
from . import message
from scopt.mpu.business.db import transaction
from scopt.util import message as msg_util
from scopt.util.message_types import INTEGER, STRING


def _request_model_mapping():
    return {'id': 'm01_med_type.id',
            'name': 'm01_med_type.desc_i18n'}


@message(type='settings.media_type_create',
         version='0.1',
         reqd={'name': STRING(required=True)},
         resd={'id': INTEGER(required=True)})
@transaction(['lds/BDS'])
def create(data_packet):
    db = msg_util.get_db(data_packet)
    reqd = msg_util.get_request(data_packet)['reqd']
    result = db.insert('m01_med_type',
                       values=reqd,
                       mapping=_request_model_mapping())
    return msg_util.insert_response(data_packet,
                                    result,
                                    create,
                                    {'id': result})


@message(type='settings.media_type_select',
         version='0.1',
         reqd={'id': INTEGER(),
               'name': STRING()},
         resd=[{'id':INTEGER(required=True),
                'name':STRING(required=True)}])
@transaction(['lds/BDS'])
def select(data_packet):
    db = msg_util.get_db(data_packet)
    reqd = msg_util.get_request(data_packet)['reqd']
    resd = db.query('m01_med_type',
                    where=db.and_(reqd, 'id', 'name'),
                    mapping=_request_model_mapping(),
                    result_mapper=_map_result)
    return msg_util.ok_response(data_packet, select, resd)


def _map_result(result):
    return [{'id':row['id'], 'name':row['desc_i18n']} for row in result]


@message(type='settings.media_type_update',
         version='0.1',
         reqd={'id': INTEGER(required=True),
               'name': STRING(required=True)},
         resd={})
@transaction(['lds/BDS'])
def update(data_packet):
    db = msg_util.get_db(data_packet)
    reqd = msg_util.get_request(data_packet)['reqd']
    result = db.update_by_pk('m01_med_type',
                             reqd.get('id'),
                             values=reqd,
                             mapping=_request_model_mapping())
    return msg_util.update_response(data_packet, result, update)
